package com.controllers;

/**
 * Copyright 2010 Commerce4J.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
//package com.commerce4j.storefront.utils.gmail;

import java.util.Properties;

import javax.faces.context.FacesContext;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.model.Comment;

/**
 * Sendmail using GMAIL implementation.
 * 
 * @author carlos.quijano
 * @version $Revision$ $Date$
 */

public class EmailController implements Runnable {

	private static final String SMTP_HOST_NAME = "smtp.gmail.com";
	private static final String SMTP_PORT = "465";
	private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
	private static final String SENDER = "noreplyocchi@gmail.com";
	private static final String PASS = "FFMM1234";
	private String newLine = System.getProperty("line.separator");
	
	private String to;
	
	private String owner;
	
	public String getOwner() {
		return owner;
	}
	public void setOwner(String owner) {
		this.owner = owner;
	}
	private String taskName;
	
	private Comment comment;
	
	private int method;

	private String username;

	private String password;
	
	private String startTask;
	
	private String endTask;
	
	private String description;
	
	public EmailController(String to, String taskName,String startTask,String endTask , String username,String description,int method) {
		this.to = to;
		this.method = method;
		this.taskName = taskName;  
		this.startTask = startTask;
		this.endTask = endTask;
		this.username = username;
		this.description = description;
	}
	public EmailController(String owner,String to, Comment comment, String username, int method) {
		this.to = to;
		this.method = method;
		this.comment = comment;  
		this.username = username;
		this.owner = owner;
	}

	@Override
	public void run() {
	   if(method ==  0 )
			sendNotificationOfNewComment(to, comment);
		else if (method == 1)
			sendNotificationOfNewTask(to, taskName);
	}


	public void sendNotificationOfNewTask(String to, String taskName) {
		String[] toArray = new String[2];
		toArray[0] = to;
		toArray[1] = "noreplyocchi@gmail.com";
		try {
			sendMessage(SENDER, toArray,
					"Notificacion de una nueva asignacion de tarea por : " + username,
					"Aviso de notificacion :"+ newLine+newLine+
					"           La tarea " + taskName + " le ha sido asignada" +newLine+
					"           El comienzo de dicha tarea es el dia : " +startTask + newLine +
					"           La tarea debera estar finalizada el dia : "+endTask +newLine+newLine+
					"	  Comentario sobre la tarea: "+description+newLine+newLine+newLine+newLine+
					"Atentamente, Sistema Occhi.");
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void sendNotificationOfNewComment(String to, Comment comment) {
		String[] toArray = new String[3];
		toArray[0] = to;
		toArray[1] = owner;
		toArray[2] = "noreplyocchi@gmail.com";
		try {
			FacesContext fc = FacesContext.getCurrentInstance();
			if (fc != null) {
				username = fc.getExternalContext().getRemoteUser();
			}
			
			sendMessage(SENDER, toArray,
					"Notificacion de nuevo comentario en la tarea "+ comment.getTask().getName()  ,
					"Aviso de notificacion :  " +newLine +newLine
					+"         El usuario "+username +" ha efectuado el siguiente comentario sobre a tarea  " + comment.getTask().getName() + newLine+newLine
					+"         "+ comment.getText()+newLine+newLine+newLine+newLine+
					"Atentamente, Sistema Occhi.");
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}



	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.commerce4j.storefront.utils.SendMail#sendMessage(java.lang.String,
	 * java.lang.String[], java.lang.String, java.lang.String)
	 */
	private void sendMessage(String from, String recipients[], String subject,
			String message) throws MessagingException {

		
		
		// Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
		boolean debug = true;

		Properties props = new Properties();
		props.put("mail.smtp.host", SMTP_HOST_NAME);
		props.put("mail.smtp.auth", "true");
		props.put("mail.debug", "true");
		props.put("mail.smtp.port", SMTP_PORT);
		props.put("mail.smtp.socketFactory.port", SMTP_PORT);
		props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
		props.put("mail.smtp.socketFactory.fallback", "false");

		Session session = Session.getDefaultInstance(props,
				new javax.mail.Authenticator() {
					@Override
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(
								SENDER, PASS);
					}
				});

		session.setDebug(debug);
		Message msg = new MimeMessage(session);
		InternetAddress addressFrom = new InternetAddress(from);
		msg.setFrom(addressFrom);

		InternetAddress[] addressTo = new InternetAddress[recipients.length];
		for (int i = 0; i < recipients.length; i++) {
			addressTo[i] = new InternetAddress(recipients[i]);
		}
		msg.setRecipients(Message.RecipientType.TO, addressTo);

		// Setting the Subject and Content Type
		msg.setSubject(subject);
		msg.setContent(message, "text/plain");
		Transport.send(msg);
	}

	/**
	 * JavaBean Getter, Gets the username current value.
	 * 
	 * @return The username current value.
	 */
	public String getUsername() {
		return username;
	}

	/**
	 * JavaBean Setter, Sets value to username.
	 * 
	 * @param username
	 *            The value of username to set.
	 */
	public void setUsername(String username) {
		this.username = username;
	}

	/**
	 * JavaBean Getter, Gets the password current value.
	 * 
	 * @return The password current value.
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * JavaBean Setter, Sets value to password.
	 * 
	 * @param password
	 *            The value of password to set.
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	public String getTo() {
		return to;
	}

	public void setTo(String to) {
		this.to = to;
	}

	public int getMethod() {
		return method;
	}

	public void setMethod(int method) {
		this.method = method;
	}

	public Comment getComment() {
		return comment;
	}
	public void setComment(Comment comment) {
		this.comment = comment;
	}

	

}